package cn.uin.domain.auth.service.user.login.handle;

import cn.uin.domain.auth.adapter.repository.IAuthRepository;
import cn.uin.domain.auth.model.entity.LoginLogEntity;
import cn.uin.domain.auth.model.entity.UserInfoDetailEntity;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Auther: uIn
 * @Date: 2025/11/2 - 11 - 02 - 16:08
 * @Description: 保存登录成功日志
 * @version: 1.0
 */
@Slf4j
@Component
public abstract class AbstractAuthenticationSuccessHandler {

    @Resource
    private IAuthRepository iauthRepository;

    /**
     * 保存登录日志
     * @param request
     * @param authentication
     * @param loginType
     */
    protected void saveLoginLog(HttpServletRequest request, Authentication authentication, Integer loginType) {
        log.info("验证成功 保存登录日志！");
        LoginLogEntity log = new LoginLogEntity();
        WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
        String username = null;
        if (authentication instanceof UsernamePasswordAuthenticationToken) {
            UserInfoDetailEntity userInfoDetailEntity = (UserInfoDetailEntity) authentication.getPrincipal();
            username = userInfoDetailEntity.getUsername();
        } else {
            username = (String) authentication.getPrincipal();
        }
        log.setUsername(username);
        log.setIp(details.getRemoteAddress());
        log.setLoginType(loginType);
        log.setLoginTime(new Date());

        String userAgent = request.getHeader("User-Agent");
        UserAgent ua = UserAgent.parseUserAgentString(userAgent);
        // 获取浏览器信息
        Browser browser = ua.getBrowser();
        String browserName = browser.getName();
        log.setBrowser(browserName);
        Version browserVersion = ua.getBrowserVersion();
        if (!ObjectUtils.isEmpty(browserVersion)) {
            log.setBrowserVersion(browserVersion.getVersion());
        }

        // 获取操作系统信息
        OperatingSystem os = ua.getOperatingSystem();
        String osName = os.getName();
        log.setOs(osName);

        // 获取设备类型（PC/手机/平板等）
        String deviceType = os.getDeviceType().getName();
        log.setDeviceType(deviceType);
        iauthRepository.saveLoginLog(log);
    }

}
